package net.wofly.sale.order.service.impl;

import net.wofly.common.util.FileTypeAddress;
import net.wofly.common.util.Identities;
import net.wofly.sale.order.domain.PayInfoPic;
import net.wofly.sale.order.repository.PayInfoPicRepository;
import net.wofly.sale.order.service.IPayInfoPicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service("iPayInfoPicService")
@Transactional
public class PayInfoPicServiceImpl implements IPayInfoPicService {
    
    @Autowired
    PayInfoPicRepository payInfoPicRepository;
    
    @Override
    public PayInfoPic save(PayInfoPic entity) {
        return payInfoPicRepository.save(entity);
    }
    
    @Override
    public void delete(PayInfoPic entity) {
        payInfoPicRepository.delete(entity);
    }
    
    @Override
    public void delete(String key) {
        payInfoPicRepository.delete(key);
    }
    
    /**
     * 根据OrderID删除
     *
     * @param orderID
     */
    @Override
    public void deleteByOrderID(String orderID) {
        payInfoPicRepository.deleteByOrderID(orderID);
    }
    
    @Override
    public PayInfoPic findOne(String key) {
        return payInfoPicRepository.findOne(key);
    }
    
    @Override
    public List<PayInfoPic> save(List<PayInfoPic> entityList) {
        return (List<PayInfoPic>) payInfoPicRepository.save(entityList);
    }
    
    @Override
    public void savePayInfoPics(String orderID, String picUrls) {
        if (StringUtils.isEmpty(picUrls)) {
            return;
        }
        deleteByOrderID(orderID);
        Long modifyDate = System.currentTimeMillis();
        List<PayInfoPic> payInfoPics = new ArrayList<>();
        String[] urls = picUrls.split("\\|");
        for (int i = 0; i < urls.length; i++) {
            PayInfoPic payInfoPic = new PayInfoPic();
            payInfoPic.setOrderID(orderID);
            payInfoPic.setOrderPayInfoPicID(Identities.uuid2());
            payInfoPic.setImgType(FileTypeAddress.支付单据图片.getValue());
            payInfoPic.setImgUrl(urls[i]);
            payInfoPic.setSequenceNumber(i);
            payInfoPic.setModifyDate(modifyDate);
            payInfoPics.add(payInfoPic);
        }
        save(payInfoPics);
    }
    
    @Override
    public List<PayInfoPic> findByOrderID(String orderID) {
        return payInfoPicRepository.findByOrderID(orderID);
    }
    
}
